package com.post.bridge.client;

import com.post.remote.IRemoteMessageHandler;

import android.app.Application;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
/**
 * C Bridge
 * @author Ge Liang
 *
 */
public class RemoteClient {
	static{
    	System.loadLibrary("post");
	}
	private static final String TAG = "PostBridge-J";
	public static final int ERR_NOT_INIT = -1;
	public static final int ERR_NO_ERR = 0;
	public static com.post.remote.client.RemoteClient remoteClientStub ;
	public static native void handleJSONMessage( String message);
	public static native void handleByteMessage( int action, byte[] data);
	public static int sendByteMessage( int pAction, byte[] pData){
		Log.i(TAG,"sendByteMessage action"+pAction+" data"+pData[0]);

		if (remoteClientStub!=null) {
			try {
				remoteClientStub.sendMessage(pAction,pData);
				return ERR_NO_ERR;
			} catch (Exception e) {
				e.printStackTrace();
				return ERR_NOT_INIT;
			}
		}
		Log.w(TAG,"Not Init ");
		return ERR_NOT_INIT;
	}
	public static int sendJSONMessage( String pMessage){
		Log.i(TAG,"sendJSONMessage "+pMessage);
		if (remoteClientStub!=null) {
			try {
				remoteClientStub.sendMessage(pMessage);
				return ERR_NO_ERR;
			} catch (Exception e) {
				e.printStackTrace();
				return ERR_NOT_INIT;
			}
		}
		Log.w(TAG,"Not Init ");
		return ERR_NOT_INIT;
	}
	public static void init (Application pApp,String pPackName){
		if (TextUtils.isEmpty(pPackName)) {
			remoteClientStub = new com.post.remote.client.RemoteClient(pApp);
		}else{
			remoteClientStub = new com.post.remote.client.RemoteClient(pApp,pPackName);
		}
		remoteClientStub.addListener(new IRemoteMessageHandler() {
			
			@Override
			public void handleMessengerConnect(Messenger pMsger) {
				
			}
			
			@Override
			public void handleMessage(int action, byte[] bytes) {
				Log.i(TAG,"handleMessage bytes:"+bytes);
				handleByteMessage(  action,  bytes);
			}
			
			@Override
			public void handleMessage(String json) {
				Log.i(TAG,"handleMessage json:"+json);
				handleJSONMessage(json);
			}
		});
	}
}
